<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\User;

use Think\Log;
use Think\Model;

class CommissionLog extends \Service\Common\BaseModel
{
    protected $name = 'commission_log';

    const COMMISSION_TYPE_PAY = 0;//代付佣金
    const COMMISSION_TYPE_SALE1 = 1;//结缘豆
    const COMMISSION_TYPE_SALE2 = 2;//惜缘豆
    const COMMISSION_TYPE_MANAGE = 3;//管理层佣金
    const COMMISSION_TYPE_JINGPAI = 12;//红豆
    const COMMISSION_TYPE_ZUANSHI = 13;//一星红豆
    const COMMISSION_TYPE_HUANGGUAN = 14;//二星红豆
    const COMMISSION_TYPE_HUANGUANDASHI = 15;//三星红豆
    const COMMISSION_TYPE_ZHIZUN = 16;//四星红豆
    const COMMISSION_TYPE_WUXING = 17;//五星红豆
    const COMMISSION_TYPE_DAILI = 18;//推荐代理分成

    const COMMISSION_TYPE = [
        self::COMMISSION_TYPE_PAY => '一级返利',
        self::COMMISSION_TYPE_SALE1 => '团队奖励',
        self::COMMISSION_TYPE_SALE2 => '二级返利',
        self::COMMISSION_TYPE_MANAGE => '复消奖',
        self::COMMISSION_TYPE_JINGPAI => '代理奖',
        self::COMMISSION_TYPE_ZUANSHI => '一星红豆',
        self::COMMISSION_TYPE_HUANGGUAN => '二星红豆',
        self::COMMISSION_TYPE_HUANGUANDASHI => '三星红豆',
        self::COMMISSION_TYPE_ZHIZUN => '四星红豆',
        self::COMMISSION_TYPE_WUXING => '五星红豆',
        self::COMMISSION_TYPE_DAILI => '推荐代理分成',
    ];

    const SETTLE_NO = 0;  //未结算
    const SETTLE_YES = 1;  //已结算
    const SETTLE_STATUS = ["未结算","已结算"];
    
    //添加代理奖记录
    public function addAgentBoundsCommission($uid, $agentFee, $percent,$settle_id)
    {
    	$commissionLogId = $this->add([
    			      'uid' => $uid,
    			      'type' => self::COMMISSION_TYPE_DAILI,
    			      'settle_status' => 0,
    			      'settle_id' => $settle_id,
    			      'money' => $agentFee*$percent,
    			      'percent' => $percent,
    			      'title' => '推荐代理分成',
    			      'order_contribution'=>$agentFee,
    			      'create_time' => date('Y-m-d H:i:s'),
    			      'settle_time' => date('Y-m-d H:i:s'),
    			]);
    	if (!$commissionLogId) {
    		throw new \Exception("佣金日志插入失败");
    	}
    	
    	return true;
    }

    //销售佣金详情
    public function commissionSaleDetail($uid, $data, $page_num = 1, $page_size = 5)
    {
        $where = [
            'uid' => $uid,
            'order_uid' => $data['uid'],
            'type' => $data['level'],
        ];
        $list = $this
            ->where([
                'uid' => $uid,
                'order_uid' => $data['uid'],
                'type' => $data['level'],
            ])
            ->order('id desc')
            ->page($page_num, $page_size)
            ->select();
        $count = $this->where($where)->count();
        return [
            $list,
            $page_count = $count,
            $page_total = ceil($count / $page_size),
            $total_commission = $this->getUpTotalSaleCommission($uid, $data['uid'], $data['level']),
            $user = OE('user')->getUserInfo($data['uid'])
        ];
    }

    //获取给上级的总佣金收益
    public function getUpTotalSaleCommission($uid, $order_uid, $level)
    {
        $total_commission = $this->where([
            'uid' => $uid,
            'order_uid' => $order_uid,
            'type' => $level,
        ])->sum('money');
        return get_decimal($total_commission);
    }

    //分红佣金列表
    public function commissionBonusList($uid, $level, $page_num = 1, $page_size = 5)
    {
        $where = [
            'uid' => $uid,
            'type' => $level
        ];
        $list = (array)$this->where($where)->order('id desc')->page($page_num, $page_size)->select();
        foreach ($list as &$row) {
            switch ($level) {
                case 2:
                    $title = "订单：{$row['order_no']}";
                    break;
                case 14:
                    $title = date('m') . "月分红";
                    break;
                default:
                    $title = date('Y') . "年分红";
            }
            $row['title'] = $title;
        }
        $count = $this->where($where)->count();
        return [
            $list,
            $page_count = $count,
            $page_total = ceil($count / $page_size),
            $total_bonus = get_decimal($this->where($where)->sum('money'))
        ];
    }

    //销售佣金列表
    public function commissionSaleList($uid, $level, $page_num = 1, $page_size = 5)
    {
        list($list, $page_count, $page_total) = OE('user')->getSubUserList($uid, $level, $page_num, $page_size);

        foreach ($list as &$row) {
            $row['total_commission'] = $this->getUpTotalSaleCommission($uid, $row['uid'], $level);
        }
        return [
            $list,
            $page_count,
            $page_total,
            $total_commission = get_decimal($this->where(['uid' => $uid, 'type' => $level])->sum('money'))
        ];
    }

    //佣金列表
    public function commissionList($uid, $type, $page_num = 1, $page_size = 5)
    {
        $where = [
            'uid' => $uid,
            'type' => $type
        ];
        $list = (array)$this->where($where)->order('id desc')->page($page_num, $page_size)->select();
        foreach ($list as &$row) {
            $order = O('order')->getDetailByOrderNO($row['order_no']);
            $row['title'] = "{$order['order_owner']}({$order['order_owner_mobile']})的订单 {$row['title']}";
            $row['type_label'] = self::COMMISSION_TYPE[$row['type']];
        }
        $count = $this->where($where)->count();
        return [
            $list,
            $page_count = $count,
            $page_total = ceil($count / $page_size),
            $total_commission = get_decimal($this->where($where)->sum('money'))
        ];
    }

    //佣金列表所有
    public function commissionListAll($uid)
    {
        $where = [
            'uid' => $uid,
        ];
        $list = (array)$this->where($where)->order('id desc')->select();
        foreach ($list as &$row) {
            $order = O('order')->getDetailByOrderNO($row['order_no']);
            $row['title'] = "{$order['order_owner']}({$order['order_owner_mobile']})的订单 {$row['title']}";
            $row['type_label'] = self::COMMISSION_TYPE[$row['type']];
            $row['settle_status_label'] = self::SETTLE_STATUS[$row['settle_status']];
        }
        $count = $this->where($where)->count();
        return [
            $list,
            $total_commission = get_decimal($this->where($where)->sum('money'))
        ];
    }

    //佣金列表所有
    public function commissionListAllNew($param, $uid)
    {
        $where = [
            'uid' => $uid,
        ];
        if($param['type'] == 1) $where['type'] = 0;
        if($param['type'] == 2) $where['type'] = 2;
        $list = (array)$this->where($where)->order('id desc')->select();
        foreach ($list as &$row) {
            $order = O('order')->getDetailByOrderNO($row['order_no']);
            $row['title'] = "{$order['order_owner']}({$order['order_owner_mobile']})的订单 {$row['title']}";
            $row['type_label'] = self::COMMISSION_TYPE[$row['type']];
            $row['settle_status_label'] = self::SETTLE_STATUS[$row['settle_status']];
        }
        $count = $this->where($where)->count();
        $total_commission = get_decimal($this->where(['uid' => $uid])->sum('money'));
        $month_start = date('Y-m-01 00:00:00');
        $month_end = date('Y-m-01 00:00:00', strtotime('+1months'));
        $month_total_commission = get_decimal($this->where([
            'uid' => $uid,
            'create_time' => [['EGT', $month_start], ['LT', $month_end]]
        ])->sum('money'));
        $day_total_commission = get_decimal($this->where([
            'uid' => $uid,
            'create_time' => [['EGT', date('Y-m-d 00:00:00')], ['LT', date('Y-m-d 23:59:59')]]
        ])->sum('money'));
        return [
            $list,
            $total_commission,
            $month_total_commission,
            $day_total_commission,
        ];
    }

    //销售佣金
    public function addSaleCommission($uid, $money, $percent, $order, $level)
    {
        $type = $level == 1 ? self::COMMISSION_TYPE_SALE1 : self::COMMISSION_TYPE_SALE2;
        $this->_add($uid, $money, $percent, $order, $type);
    }

    //管理层佣金
    public function addManageCommission($uid, $money, $percent, $order)
    {
        $this->_add($uid, $money, $percent, $order, self::COMMISSION_TYPE_MANAGE);
    }

    //代付佣金
    public function addPayCommission($uid, $money, $percent, $order)
    {
        $order['title'] = $order['order_no'];
        $this->_add($uid, $money, $percent, $order, self::COMMISSION_TYPE_PAY);
    }

    //分享奖
    public function shareCommission($order)
    {

        //推荐人没有达到领取佣金级别,UID为新注册会员id
        $commission_min_level = C('COMMISSION_MIN_LEVEL', null, 0);
        $refererList = O('user')->getRefererTree($order['uid']);

        /*$all_money = 100;//总奖励
        $all_g_money = 0;//已发出
        $v0_money = 70;
        $v1_money = 90;
        $v2_money = 100;
        $v3_money = 100;*/

        $all_money = $order['order_contribution']*1;//总奖励
        $all_g_money = 0;//已发出
        $v0_money = $all_money*0.35;
        $v1_money = $all_money*0.45;
        $v2_money = $all_money*0.5;
        $v3_money = $all_money*0.5;

        foreach ($refererList as $row) {


            if ($row['vip_level'] >= $commission_min_level) {
               switch ($row['vip_level']){
                    case 1:
                        $give_money = $v0_money - $all_g_money;
                        $commission_min_level = 2;

                        break;
                    case 2:
                        $give_money = $v1_money - $all_g_money;
                        $commission_min_level = 3;

                        break;
                   case 3:
                       $give_money = $v2_money - $all_g_money;
                       $commission_min_level = 4;

                       break;
                   case 4:
                       $give_money = $v3_money - $all_g_money;
                       $commission_min_level = 5;

                       break;

                }

                $all_money -= $give_money;
                $all_g_money += $give_money;


                $referer_uid = $row['uid'];

                if (!$referer_uid) {
                    return 0;
                }

                //实际给的分享奖金
                $money = $give_money;
                if (!$money) {
                    return 0;
                }

                $this->_add($referer_uid, $money, 1, $order, self::COMMISSION_TYPE_SALE1, $settle_status = 1);

                //资金记录
                OE('user')->commissionShare($referer_uid, $money, $order['id']);

                if($commission_min_level >=5 || $all_money <= 0){
                    break;
                }

            }
        }

    }


    //团队奖励
    public function shareCommissionGxh($order, $team_money)
    {

        //推荐人没有达到领取佣金级别,UID为新注册会员id
        $commission_min_level = C('COMMISSION_MIN_LEVEL', null, 0);

        $refererList = O('user')->getRefererTree($order['uid']);


        foreach ($refererList as $row) {


            if ($row['vip_level'] >= $commission_min_level) {
                $referer_uid = $row['uid'];
                if (!$referer_uid) {
                    return 0;
                }
                //实际给的分享奖金
//                $money = $give_money;


                $this->_add($referer_uid, $team_money, 1, $order, self::COMMISSION_TYPE_SALE1, $settle_status = 1);

                //资金记录
                OE('user')->commissionShare($referer_uid, $team_money, $order['id']);
            }


        }

    }

    //复销佣金
    public function addrebuyCommission($order)
    {

        //根据订单找到商品。是否来自重消商城
        $ordergoods = M('order_goods')->where(['order_id' =>$order['id']])->select();

        $order_contribution = 0;

        if($ordergoods){
            foreach ($ordergoods as $row) {
                $goodsinfo = M('goods')->where(['id'=>$row['goods_id']])->find();

                if($goodsinfo['is_vip'] == 1){
                    $order_contribution =+ $goodsinfo['rebuy_contribution'] * $row['buy_num'];
                }
            }

        }

        if($order_contribution > 0) {

            //贡献值大于0

            $order['title'] = $order['order_no'];
            $refererList = O('user')->getRefererTree($order['uid'],5);//获取向上的5代
//        $percent = C('BUY_SERVICE_COMMISSION', null, 0);
            $commission_min_level = C('COMMISSION_MIN_LEVEL', null, 0);
            foreach ($refererList as $row) {
                //推荐人没有达到领取佣金级别
                if ($row['vip_level'] < $commission_min_level) {
                    continue;
                }

                //没有佣金比例
                $percent = 0.05;
                $money = $percent * $order_contribution;
                if (!$money) {
                    break;
                }

                $this->_add($row['uid'], $money, $percent, $order, self::COMMISSION_TYPE_MANAGE, $settle_status = 1);

                //资金记录
                OE('user')->commissionRebuy($row['uid'], $money, $order['id']);
            }

        }


    }

    //代理佣金
    public function agentCommission($order)
    {

        //根据订单找到商品。是否支持代理结算
        $ordergoods = M('order_goods')->where(['order_id' =>$order['id']])->select();

        $order_contribution = 0;

        if($ordergoods){
            foreach ($ordergoods as $row) {
                $goodsinfo = M('goods')->where(['id'=>$row['goods_id']])->find();
                if($goodsinfo['is_agent_settle'] == 1){
                    if($order['order_type'] == 1){
                        $order_contribution =+ $goodsinfo['rebuy_contribution'] * $row['buy_num'];
                    }else{
                        $order_contribution =+ $goodsinfo['contribution'] * $row['buy_num'];
                    }
                }
            }

        }

        if($order_contribution > 0){

            //贡献值大于0
            //找代理 先找县代理，再找区代理

            //获取订单的收货地址
            $area = explode(',',$order['area']);
            $shicode = $area[0].','.$area[1];//城市码
//            $shicode = $order['area'];
            $xiancode = $order['area'];//县区码

            $xian_agentinfo = M('agent')->where(['location' => $xiancode,'level'=>0,'check_status' => 1])->find();
//            $shi_agentinfo = M('agent')->where(['location' => ['like',$shicode.'%'],'level' =>1,'check_status' => 1])->find();
            $shi_agentinfo = M('agent')->where(['location' => $shicode,'level' =>1,'check_status' => 1])->find();

            if($xian_agentinfo) {
                //有县级代理

                //没有佣金比例
                $percent = 0.05;
                $money = $percent * $order_contribution;

                $this->_add($row['uid'], $money, $percent, $order, self::COMMISSION_TYPE_JINGPAI, $settle_status = 1);

                //资金记录
                OE('user')->commissionAgent($xian_agentinfo['uid'], $money, $order['id']);

                $this->add_agent_referer($shi_agentinfo['referee_uid'],$money,$order);

                if($shi_agentinfo){

                    $percent = 0.05;
                    $money = $percent * $order_contribution;

                    $this->_add($row['uid'], $money, $percent, $order, self::COMMISSION_TYPE_JINGPAI, $settle_status = 1);

                    //资金记录
                    OE('user')->commissionAgent($shi_agentinfo['uid'], $money, $order['id']);
                    $this->add_agent_referer($shi_agentinfo['referee_uid'],$money,$order);
                }

            }else{

                //没有县代理

                if($shi_agentinfo){

                    $percent = 0.1;
                    $money = $percent * $order_contribution;

                    $this->_add($row['uid'], $money, $percent, $order, self::COMMISSION_TYPE_JINGPAI, $settle_status = 1);

                    //资金记录
                    OE('user')->commissionAgent($shi_agentinfo['uid'], $money, $order['id']);

                    $this->add_agent_referer($shi_agentinfo['referee_uid'],$money,$order);

                }


            }

        }

    }

    public function add_agent_referer($referer_uid,$order_contribution,$order){


        $percent = 0.1;
        $money = $percent * $order_contribution;

        $order['order_contribution'] = $order_contribution;

        $this->_add($referer_uid, $money, $percent, $order, self::COMMISSION_TYPE_DAILI, $settle_status = 1);

        //资金记录
        OE('user')->commissionAgent2($referer_uid, $money, $order['id']);

    }


    //月结时处理业绩奖佣金
    public function addyejiCommission()
    {

        //根据佣金记录，找到未结算的type=2的业绩佣金，时间是上个月

        $lastmonth_start = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m")-1,1,date("Y")));
        $lastmonth_end = date("Y-m-d H:i:s",mktime(23,59,59,date("m") ,0,date("Y")));

        $commission_total_money = M('commission_log')->where([
			        		'type' =>self::COMMISSION_TYPE_SALE2,
			        		'settle_status' => 0,
			        		//'create_time'=>[
			        		 //  'between',[$lastmonth_start,$lastmonth_end]]
			        		])->sum('money');
        if ($commission_total_money <= 0){
        	throw new \Exception("没有可结算的记录");
        }
        $list = M('user')->where(['vip_level' => 4])->getField('uid',true);
        $num = count($list);
        if ($num > 0) {	
        $money = get_decimal($commission_total_money/$num);
	        foreach ($list as $uid){
	        	//资金记录
	        	OE('user')->commissionYeji($uid, $money, 0);
	        }
        }
        $result =  M('commission_log')->where([
			        		'type' =>self::COMMISSION_TYPE_SALE2,
			        		'settle_status' => 0,
			        		//'create_time'=>[
			        		 //  'between',[$lastmonth_start,$lastmonth_end]]
			        		])->save(['settle_status' => 1]);
        if ($result === false) {
        	throw new \Exception("更新结算状态失败");
        }
      return true;
    }
    
    


    //销售佣金
    public function addBuyCommission($order)
    {
        $order['title'] = $order['order_no'];
        //推荐人没有达到领取佣金级别
        $commission_min_level = C('COMMISSION_MIN_LEVEL', null, 0);
        $refererList = O('user')->getRefererTree($order['uid']);
        $referer_uid = 0;
        foreach ($refererList as $row) {
            if ($row['vip_level'] >= $commission_min_level) {
                $referer_uid = $row['uid'];
                break;
            }
        }
        if (!$referer_uid) {
            return 0;
        }

        //没有佣金比例
        $percent = C('BUY_COMMISSION', null, 0);
        $money = $order['order_contribution'] * $percent;
        if (!$money) {
            return 0;
        }

        $this->_add($referer_uid, $money, $percent, $order, self::COMMISSION_TYPE_SALE1, $settle_status = 1);

        //资金记录
        OE('user')->commissionSale($referer_uid, $money, $order['id'], 1);

        return [
            $money,
            $referer_uid
        ];
    }


    //服务佣金
    public function addBuyServiceCommission($uid, $order, $money)
    {
        $order['title'] = $order['order_no'];
        $refererList = O('user')->getRefererTree($uid);
        $percent = C('BUY_SERVICE_COMMISSION', null, 0);
        $commission_min_level = C('COMMISSION_MIN_LEVEL', null, 0);
        foreach ($refererList as $row) {
            //推荐人没有达到领取佣金级别
            if ($row['vip_level'] < $commission_min_level) {
                continue;
            }

            //没有佣金比例
            $order['order_contribution'] = $money;
            $money = $percent * $money;
            if (!$money) {
                break;
            }

            $this->_add($row['uid'], $money, $percent, $order, self::COMMISSION_TYPE_SALE2, $settle_status = 1);

            //资金记录
            OE('user')->commissionSale($row['uid'], $money, $order['id'], 2);
        }
    }

    //分红
    public function addBoundsCommission($uid, $money, $percent, $order, $type)
    {
        $this->_add($uid, $money, $percent, $order, $type);
    }

    public function _add($uid, $money, $percent, $order, $type, $settle_status = 0)
    {
        if ($money <= 0) {
            return;
        }

        //佣金日志
        $data = [
            'create_time' => date('Y-m-d H:i:s'),
            'type' => $type,
            'uid' => $uid,
            'title' => '',
            'money' => $money,
            'percent' => $percent,
            'order_uid' => $order['uid'] ?: 0,
            'order_no' => $order['order_no'] ?: 0,
            'settle_id' => $order['settle_id'] ?: 0,//代付佣金没有结算id
            'order_contribution' => $order['order_contribution'] ?: 0,
            'settle_status' => $settle_status
        ];
        $settle_status AND $data['settle_time'] = date('Y-m-d H:i:s');

        $insert_id = $this->add($data);
        if (!$insert_id) {
            throw new \Exception("佣金日志插入失败");
        }
    }



    const MANAGER_AWARD = 1;
    //佣金结算
    public function payCommissionCallback($order)
    {

        $team_money = 0;  //团队奖励
        $one_money = 0;    //上级推荐奖励
        $tow_money = 0;     //上上级推荐奖励
        $manager_money = 0;     //领导折扣奖
        foreach($order['goods'] as $k => $v){
            $goods_detail = M('goods')->where(['id' => $v['goods_id']])->find();
            if($goods_detail['type'] != 16){
                $team_money += $v['buy_num']*$v['team_cps'];
                $one_money += $v['buy_num']*$v['one_cps'];
                $tow_money += $v['buy_num']*1;
                $manager_money += $v['buy_num']*1;
            }
        }
        //团队返利
//        if($team_money>0)   $this->shareCommissionGxh($order, $team_money);

        //manager_money
        $this->managerMoney($order, $manager_money);

        //推荐人奖励
        $user_data = M('user')->where(['uid' => $order['uid']])->find();
        if($user_data['referer_id']){
            $refer_user = M('user')->where(['uid' => $user_data['referer_id']])->find();
            if($refer_user['vip_level'] > 0){
                $this->_add($user_data['referer_id'], $one_money, 0, $order, 0, $settle_status = 1);
                //资金记录
                OE('user')->commissionSale($user_data['referer_id'], $one_money, $order['id'], 1);
            }

            //上上级奖励
            if($refer_user['referer_id']){
                $refer2_user = M('user')->where(['uid' => $refer_user['referer_id']])->find();
                if($refer2_user['vip_level']>0){
                    $this->_add($refer_user['referer_id'], $tow_money, 0, $order, 2, $settle_status = 1);
                    //资金记录
                    OE('user')->commissionSale($refer_user['referer_id'], $tow_money, $order['id'], 1);
                }
            }
        }




    }

    public function managerMoney($order, $manager_money){
        $user_data = M('user')->where(['uid' => $order['uid']])->find();
        $tg_uid = $user_data['referer_id'];
        while(true){
            if($tg_uid == 0) break;
            $user = M('user')->where(['uid' => $tg_uid])->find();
            if(!$user) break;
            if($user['vip_level'] == 2){
                $this->_add($tg_uid, $manager_money, 0, $order, 3, $settle_status = 1);
                //资金记录
                OE('user')->commissionSale($tg_uid, $manager_money, $order['id'], 1);
                break;
            }
            $tg_uid = $user['referer_id'];
        }
    }


    //业绩提成
    public function yejiCommission($order)
    {
        //找符合条件的会员 vip3才有资格

        //$referer_tree = M('user')->where(['manage_level' => 4])->select();
        $range_percent = 0.02;

        //foreach ($referer_tree as $row) {

            //佣金记录 ，此订单贡献值 * 比例
            $money = get_decimal($order['order_contribution'] * $range_percent);
            $this->_add(0, $money, $range_percent, $order, self::COMMISSION_TYPE_SALE2, $settle_status = 0);
        //}
    }

    //管理层提成
    public function manageCommission($order)
    {
        //推荐人树
        $referer_tree = OE('user')->getRefererTree($order['uid']);
        $prev_level = 0;
        $commission_min_level = C('COMMISSION_MIN_LEVEL', null, 0);
        foreach ($referer_tree as $row) {
            //佣金领取 最低级别限制
            if ($row['vip_level'] < $commission_min_level) {
                continue;
            }

            list($range_percent, $max_level) = $this->getRangePercent($row['vip_level'], $prev_level);
            $prev_level = $row['vip_level'];

            //佣金记录
            $money = get_decimal($order['order_contribution'] * $range_percent);
            $this->_add($row['uid'], $money, $range_percent, $order, $max_level, $settle_status = 0);
        }
    }

    //获取管理级别佣金比例
    public function getRangePercent($current_level, $prev_level)
    {
        $inc_percent = 0;
        $level_list = get_list_config('BONUS_COMMISSION', true);
        $max_level = 0;
        foreach ($level_list as $key => $value) {
            if ($key > $prev_level && $key <= $current_level) {
                $value['month_commission'] AND $max_level = 10 + $key;
                $inc_percent += $value['month_commission'] ?: 0;
            }
        }
        return [$inc_percent, $max_level];
    }

    //月分红
    public function genMonthBounds()
    {

        $key = date('Ym') . 'bounds';

       if (S($key)) {
            throw new \Exception("当月已经分红了");
        }
        S($key, 1);

        try {
            $this->startTrans();

            //级差结算
//            $this->settleRangeCommission();
            $this->addyejiCommission();

            //商城月分红
//            $this->genMallMonthBonus();

            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new \Exception($e->getMessage());
        }
    }

    //商城月分红
    public function genMallMonthBonus()
    {
        $list = get_list_config('BONUS_COMMISSION', true);
        $min_vip_level = 0;
        $percent = 0;
        foreach ($list as $row) {
            if ($percent = $row['mall_month_commission']) {
                $min_vip_level = $row['type'];
                break;
            }
        }

        $users = M('user')->where(['vip_level' => ['egt', $min_vip_level]])->select();
        $order_contribution = M('order')->where([
            'pay_status' => 1,
            'create_time' => [
                ['egt', date('Y-m-01')],
            ]
        ])->sum('order_contribution');
        $money = get_decimal($order_contribution * $percent / count($users));

        foreach ($users as $row) {
            $this->_add($row['uid'], $money, $percent, ['order_contribution' => $order_contribution], $min_vip_level + 10, $settle_status = 1);
            //资金记录
            OE('user')->mallMonthBonus($row['uid'], $money);
        }
    }

    //级差结算
    public function settleRangeCommission()
    {
        $list = $this->where([
            'type' => ['in', [
                self::COMMISSION_TYPE_JINGPAI,//红豆
                self::COMMISSION_TYPE_ZUANSHI,//一星红豆
        		self::COMMISSION_TYPE_HUANGGUAN,//二星红豆
            ]],
            'settle_status' => 0
        ])->select();
        foreach ($list as $row) {
            //资金记录
            OE('user')->commissionManage($row['uid'], $row['money'], $row['id']);

            $update = $this->save([
                'id' => $row['id'],
                'settle_status' => 1,
                'settle_time' => date('Y-m-d H:i:s'),
            ]);
            if ($update === false) {
                throw new \Exception("更新结算状态失败");
            }
        }
    }

    //年分红
    public function genYearBounds()
    {
        throw new \Exception("年度分红未开启");
        $key = date('Y') . 'bounds';
        if (S($key)) {
            throw new \Exception("当年已经分红了");
        }
        S($key, 1);

        try {
            $this->startTrans();

            foreach (['mall_year_commission', 'mall_year_commission2'] as $k) {
                $list = get_list_config('BONUS_COMMISSION', true);
                $min_vip_level = 0;
                $percent = 0;
                foreach ($list as $row) {
                    if ($percent = $row[$k]) {
                        $min_vip_level = $row['type'];
                        break;
                    }
                }

                $users = M('user')->where(['vip_level' => ['egt', $min_vip_level]])->select();
                $order_contribution = M('order')->where([
                    'pay_status' => 1,
                    'create_time' => [
                        ['egt', date('Y-01-01')],
                    ]
                ])->sum('order_contribution');
                $money = get_decimal($order_contribution * $percent / count($users));

                foreach ($users as $row) {
                    $this->_add($row['uid'], $money, $percent, ['order_contribution' => $order_contribution], $min_vip_level + 10, $settle_status = 1);
                    //资金记录
                    OE('user')->mallYearBonus($row['uid'], $money);
                }
            }

            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new \Exception($e->getMessage());
        }
    }

    public function teamSettle()
    {
        Log::w_log("######11111");
        $batch_id = OE('batch')->exec('\Service\User\Service::shellTeamSettle', '团队返利月结算');
        Log::w_log("######2222");
        return $batch_id;
    }



    public function shellTeamSettle()
    {
        Log::w_log("######shellTeamSettle--111");
        try {
            $model = new Model();
            $start = date('Y-m-01', strtotime("-1 month"));
            $end = date('Y-m-01');
//            $start = '2019-06-01';
//            $end = '2019-07-01';
            $sql = "SELECT  * FROM `k_order`
WHERE pay_status=1 AND pay_time>='$start 00:00:00'
AND pay_time<'$end 00:00:00';";
            $list = $model->query($sql);
            foreach($list as &$item){
                $ret1 = M('order_goods')->field('*')->where(['order_id' => $item['id']])->select();
                foreach($ret1 as $k => $v){
                    $goods_detail = M('goods')->where(['id' => $v['goods_id']])->find();
                    if($goods_detail['type'] != 16){
                        $item['buy_num'] = 0;
                    }else{
                        $item['buy_num'] = $ret1['buy_num']?$ret1['buy_num']:0;
                    }
                }
            }
            O('batch')->setCount(count($list));
            $this->startTrans();
            //O('batch')->setTotalStep(3);
            foreach ($list as $v) {
                $user_data = M('user')->where(['uid' => $v['uid']])->find();
                $tj_uid = $user_data['referer_id'];
                $uid_arr = [];
                $team_money_total = $v['buy_num']*6;
                while(true){
                    if($team_money_total <=0) break;
                    if(in_array($tj_uid, $uid_arr)) {
                        Log::w_log("order_uid: {$v['uid']} tj_uid: {$tj_uid}");
                        throw new \Exception('推荐关系存在问题');
                    }
                    $uid_arr[] = $tj_uid;
                    $user = M('user')->where(['uid' => $tj_uid])->find();
                    if(!$user) break;
                    $user_team_money = $v['buy_num']*self::calcTeamMoney($tj_uid);

                    if($team_money_total>=$user_team_money){
                        $this->_add($tj_uid, $user_team_money, 1, $v, self::COMMISSION_TYPE_SALE1, $settle_status = 1);
                        //资金记录
                        OE('user')->commissionShare($tj_uid, $user_team_money, $v['id']);
                    }else{
                        $this->_add($tj_uid, $team_money_total, 1, $v, self::COMMISSION_TYPE_SALE1, $settle_status = 1);
                        //资金记录
                        OE('user')->commissionShare($tj_uid, $team_money_total, $v['id']);
                    }

                    $tj_uid = $user['referer_id'];
                    $team_money_total = $user_team_money - $user_team_money;
                }


                O('batch')->setProgress();//当前进度
            }


            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new \Exception($e->getMessage());
        }
        Log::w_log("######shellTeamSettle--9999");
    }

    const TEAM_RATE = [
        0 => 1,         //300-800件以上
        1 => 1.5,       //800-3000件
        2 => 2,       //3000-8000件
        3 => 3,       //8000-15000件
        4 => 4,       //15000-30000件
        5 => 5,       //30000-60000件
        6 => 6       //60000件以上
    ];
    public function calcTeamMoney($uid){
        $team_total = M('k_team_log')->field('sum(num) as num_total')->where(['uid' => $uid])->find();
        $num_total = $team_total['num_total']?$team_total['num_total']:0;
        $rate = 0;
        if($team_total<300){
            $rate=0;
        }elseif($num_total>=300 && $num_total<800){
            $rate=1;
        }elseif($num_total>=800 && $num_total<3000){
            $rate=1.5;
        }elseif($num_total>=3000 && $num_total<8000){
            $rate=2;
        }elseif($num_total>=8000 && $num_total<15000){
            $rate=3;
        }elseif($num_total>=15000 && $num_total<30000){
            $rate=4;
        }elseif($num_total>=30000 && $num_total<60000){
            $rate=5;
        }else{
            $rate=6;
        }

        return $rate;

    }
}